package com.nidu.demo.config.ability;

import com.alibaba.cola.exception.BizException;
import com.nidu.demo.common.exception.ErrorCodeConstants;
import com.nidu.demo.config.gateway.ConfigGateway;
import com.nidu.demo.config.model.Config;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;

/**
 * 系统配置领域服务
 *
 * @author auto
 */
@Component
@RequiredArgsConstructor
public class ConfigDomainService {

    private final ConfigGateway gateway;

    /**
     * 检查键名是否重复
     *
     * @param key 配置键名
     * @param excludeId 排除的ID
     */
    public void validateDuplicate(String key, Long excludeId) {
        Config config = gateway.getByKey(key);
        if (config != null) {
            if (excludeId == null) {
                throw new BizException(ErrorCodeConstants.CONFIG_KEY_DUPLICATE.getCode(),
                        ErrorCodeConstants.CONFIG_KEY_DUPLICATE.getMessage());
            } else if (!excludeId.equals(config.getId())) {
                throw new BizException(ErrorCodeConstants.CONFIG_KEY_DUPLICATE.getCode(),
                        ErrorCodeConstants.CONFIG_KEY_DUPLICATE.getMessage());
            }
        }
    }

    /**
     * 验证配置是否存在
     *
     * @param id 配置ID
     */
    public void validateConfig(Long id) {
        if (id != null) {
            Config config = gateway.getById(id);
            if (config == null) {
                throw new BizException(ErrorCodeConstants.CONFIG_NOT_FOUND.getCode(),
                        ErrorCodeConstants.CONFIG_NOT_FOUND.getMessage());
            }
            config.isDisable();
            config.isDeleted();
        }
    }

    /**
     * 更新配置状态
     *
     * @param id 配置ID
     * @param status 状态
     */
    public void updateStatus(Long id, Integer status) {
        // 验证配置是否存在
        validateConfig(id);
        gateway.updateStatus(id, status);
    }
} 